let Vue
class Store {
    constructor(options) {
        this.vm = new Vue({
            data: {
                state: options.state
            }
        })
        //for getters
        let getters = options.getters || {}
        this.getters = {}//当前实例
        Object.keys(getters).forEach(getterName => {

            Object.defineProperty(this.getters, getterName, {
                get: () => {
                    return getters[getterName](this.state)
                }
            })
        })
        // for mutations
        let mutations = options.mutations || {}
        this.mutations = {}
        Object.keys(mutations).forEach((mutaionName, i) => {
            this.mutations[mutaionName] = payload => {
                mutations[mutaionName](this.state, payload)
            }
        })


        //for actions
        let actions = options.actions || {}
        this.actions = {}
        Object.keys(actions).forEach((actionName, i) => {
            this.actions[actionName] = payload => {
                actions[actionName](this, payload)
            }
        })
    }
    dispatch(method, payload) {
        this.actions[method](payload)
    }
    commit = (method, payload) => {
        this.mutations[method](payload)
    }
    get state() {
        return this.vm.state
    }
}
//install 插件固定写法

const install = (v) => {
    console.log(v)
    Vue = v
    Vue.mixin({//需要在每个组件上添加$store
        beforeCreate() {
            console.log(this.$options.name)
            if (this.$options && this.$options.store) {
                //root
                this.$store = this.$options.store
            } else {
                this.$store = this.$parent && this.$parent.$store
            }
        }
    })
}

export default {
    install, Store
}